package com.innext.kjqb.ui.my.fragment;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.innext.kjqb.app.App;
import com.innext.kjqb.events.AuthenticationCenterDataEvent;
import com.innext.kjqb.events.FragmentRefreshEvent;
import com.innext.kjqb.ui.my.activity.CouponActivity;
import com.innext.kjqb.widget.loading.LoadingLayout;
import com.innext.kjqb.R;
import com.innext.kjqb.base.BaseFragment;
import com.innext.kjqb.config.Constant;
import com.innext.kjqb.dialog.AlertFragmentDialog;
import com.innext.kjqb.events.UIBaseEvent;
import com.innext.kjqb.ui.authentication.activity.PerfectInformationActivity;
import com.innext.kjqb.ui.authentication_new.activity.AuthenticationVerifityActivity;
import com.innext.kjqb.ui.main.MainActivity;
import com.innext.kjqb.ui.main.WebViewActivity;
import com.innext.kjqb.ui.my.activity.MoreActivity;
import com.innext.kjqb.ui.my.activity.TransactionRecordActivity;
import com.innext.kjqb.ui.my.bean.MoreContentBean;
import com.innext.kjqb.ui.my.contract.MyContract;
import com.innext.kjqb.ui.my.presenter.MyPresenter;
import com.innext.kjqb.util.SpUtil;
import com.innext.kjqb.util.StringUtil;
import com.innext.kjqb.util.ToastUtil;
import com.innext.kjqb.util.Tool;
import com.sobot.chat.SobotApi;
import com.sobot.chat.api.model.Information;
import com.tendcloud.tenddata.TCAgent;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * 作者：黑哥 on 2016/9/20 13:26
 * <p>
 * 更多页面
 */
public class MoreFragment extends BaseFragment<MyPresenter> implements View.OnClickListener, MyContract.View
        , SwipeRefreshLayout.OnRefreshListener {
    public static MoreFragment fragment;

    @BindView(R.id.loading_layout)
    LoadingLayout mLoadingLayout;
    @BindView(R.id.tc_progress)
    TextView mTcProgress;
    @BindView(R.id.tv_money_statu)
    TextView mMoneyStatu;
    @BindView(R.id.tv_remaining_borrow)
    TextView mTvRemainingBorrow;
    @BindView(R.id.tv_my_bank)
    TextView mTvMyBank;
    @BindView(R.id.tv_invit_code)
    TextView mTvInvitCode;
    @BindView(R.id.refresh)
    SwipeRefreshLayout mRefresh;
    @BindView(R.id.iv_query)
    ImageView mIvQuery;
    @BindView(R.id.paddingView)
    View mPaddingView;
    Unbinder unbinder;
    private MainActivity mActivity;
    private MoreContentBean mMoreContentBean;
    private int mAuthStep;
    private String mPhoneUrl;
    private String mZmxyUrl;


    public static MoreFragment getInstance() {
        if (fragment == null)
            fragment = new MoreFragment();
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_more_main;
    }

    @Override
    public void initPresenter() {
        mPresenter.init(this);
    }

    @Override
    public void loadData() {
        mActivity = (MainActivity) getActivity();
        EventBus.getDefault().register(this);
        mLoadingLayout.setStatus(LoadingLayout.Loading);
        mRefresh.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.theme_color));
        mRefresh.setOnRefreshListener(this);
        if (App.getConfig().getLoginStatus()) {
            mPresenter.getInfo();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            LinearLayout.LayoutParams paddingViewLayoutParams = (LinearLayout.LayoutParams) mPaddingView.getLayoutParams();
            paddingViewLayoutParams.height = Tool.getStatusBarHeight(getActivity());
            mPaddingView.setLayoutParams(paddingViewLayoutParams);
        }
        mTitle.setTitle(false, StringUtil.changeMobile(SpUtil.getString(Constant.CACHE_TAG_USERNAME)));
        mTitle.setRightTitle(R.mipmap.shezhi, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(mContext, "my_setting");
                TCAgent.onEvent(mContext, "my_setting");
                if (mMoreContentBean == null) {
                    mPresenter.getInfo();
                } else {
                    Intent intent = new Intent(mActivity, MoreActivity.class);
                    intent.putExtra("bean", mMoreContentBean);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            mPresenter.getInfo();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(FragmentRefreshEvent event) {
        if (UIBaseEvent.EVENT_BANK_CARD_SUCCESS == event.getType() ||//银行卡绑定或修改成功
                UIBaseEvent.EVENT_LOGIN == event.getType() || //登录成功
                UIBaseEvent.EVENT_REPAY_SUCCESS == event.getType() ||  //还款成功
                UIBaseEvent.EVENT_REALNAME_AUTHENTICATION_SUCCESS == event.getType() ||    //实名认证成功
                UIBaseEvent.EVENT_LOAN_SUCCESS == event.getType() ||   //借款申请成功
                UIBaseEvent.EVENT_LOAN_FAILED == event.getType()||
                UIBaseEvent.REFRESHINDEX == event.getType()) {   //借款申请失败
            if (UIBaseEvent.EVENT_LOGIN == event.getType()) {
                mTitle.setTitle(false, StringUtil.changeMobile(SpUtil.getString(Constant.CACHE_TAG_USERNAME)));
            }
            if (App.getConfig().getLoginStatus()) {
                mPresenter.getInfo();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshEvent(AuthenticationCenterDataEvent event) {
        if (event != null) {
            mAuthStep = event.getAuthStep();
            Log.i("mAuthStepMorefRAGMENT",event.getAuthStep()+"");
            mPhoneUrl = event.getPhoneUrl();
            mZmxyUrl = event.getZmxyUrl();
        }
    }

    /**
     * 设置数据
     */
    private void setData(final MoreContentBean mMoreContentBean) {
        if (mMoreContentBean.getCard_info() != null) {
            if (!StringUtil.isBlank(mMoreContentBean.getCard_info().getBank_name()) && !StringUtil.isBlank(mMoreContentBean.getCard_info().getCard_no_end())) {
                mTvMyBank.setText(mMoreContentBean.getCard_info().getBank_name() + "(" + mMoreContentBean.getCard_info().getCard_no_end() + ")");
            } else {
                mTvMyBank.setText("");
            }
        }
        mTvInvitCode.setText(mMoreContentBean.getInvite_code());

        if (mMoreContentBean.getMust_verify_status().equals("1")) { //认证过
            if (mMoreContentBean.getEvaluation_flag_status().equals("1")) {//风控过
                if (!mMoreContentBean.getCredit_info().getCard_amount().equals("0")) {//有额度
                    mTvRemainingBorrow.setVisibility(View.VISIBLE);
                    mTcProgress.setVisibility(View.VISIBLE);
                    mMoneyStatu.setVisibility(View.GONE);
                    setCreditLimitAnimation(mTcProgress, Integer.valueOf(mMoreContentBean.getCredit_info().getCard_amount()) / 100);
                    mTvRemainingBorrow.setText("剩余可借：" + Integer.valueOf(mMoreContentBean.getCredit_info().getCard_unused_amount()) / 100 + "元");
                    mIvQuery.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            MobclickAgent.onEvent(getActivity(), "ME_haveCredit");
                            TCAgent.onEvent(getActivity(), "ME_haveCredit");
                            new AlertFragmentDialog.Builder(mActivity)
                                    .setContent("经我们仔细评估，您当前额度为"+
                                            Integer.valueOf(mMoreContentBean.getCredit_info().getCard_amount()) / 100+"元，请保持良好的信用习惯")
                                    .setRightBtnText("更多额度")
                                    .setRightCallBack(new AlertFragmentDialog.RightClickCallBack() {
                                        @Override
                                        public void dialogRightBtnClick() {
                                            MobclickAgent.onEvent(getActivity(), "ME_moreCredit");
                                            TCAgent.onEvent(getActivity(), "ME_moreCredit");
                                            Intent intent = new Intent(mContext, WebViewActivity.class);
                                            intent.putExtra("improveUrl", mMoreContentBean.getIncrease_credit_url().getXinyongbaitiao_url());
                                            startActivity(intent);
                                        }
                                    }).setLeftBtnText("取消").setLeftCallBack(new AlertFragmentDialog.LeftClickCallBack() {
                                @Override
                                public void dialogLeftBtnClick() {
                                    MobclickAgent.onEvent(getActivity(), "ME_cancleCredit");
                                    TCAgent.onEvent(getActivity(), "ME_cancleCredit");
                                }
                            }).setCancel(false).build();
                        }
                    });
                } else {
                    mTcProgress.setVisibility(View.GONE);
                    mMoneyStatu.setVisibility(View.VISIBLE);
                    mMoneyStatu.setText("无额度");
                    mTvRemainingBorrow.setVisibility(View.GONE);
                    mIvQuery.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            MobclickAgent.onEvent(getActivity(), "ME_noCredit");
                            TCAgent.onEvent(getActivity(), "ME_noCredit");
                            new AlertFragmentDialog.Builder(mActivity)
                                    .setContent("很遗憾，经我们仔细评估，您当前无额度，请保持良好的信用习惯，点击更多借款试试吧")
                                    .setRightBtnText("更多借款")
                                    .setRightCallBack(new AlertFragmentDialog.RightClickCallBack() {
                                        @Override
                                        public void dialogRightBtnClick() {
                                            MobclickAgent.onEvent(getActivity(), "ME_moreBorrow");
                                            TCAgent.onEvent(getActivity(), "ME_moreBorrow");
                                            Intent intent = new Intent(mContext, WebViewActivity.class);
                                            intent.putExtra("improveUrl", mMoreContentBean.getIncrease_credit_url().getShouyijie_url());
                                            startActivity(intent);
                                        }
                                    }).setLeftBtnText("取消").setLeftCallBack(new AlertFragmentDialog.LeftClickCallBack() {
                                @Override
                                public void dialogLeftBtnClick() {
                                    MobclickAgent.onEvent(getActivity(), "ME_cancleMoreBorrow");
                                    TCAgent.onEvent(getActivity(), "ME_cancleMoreBorrow");
                                }
                            }).setCancel(false).build();
                        }
                    });
                }
            } else {
                mTcProgress.setVisibility(View.GONE);
                mMoneyStatu.setVisibility(View.VISIBLE);
                mMoneyStatu.setText("额度评估中");
                mTvRemainingBorrow.setVisibility(View.GONE);
                mIvQuery.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MobclickAgent.onEvent(getActivity(), "ME_evaluating");
                        TCAgent.onEvent(getActivity(), "ME_evaluating");
                        new AlertFragmentDialog.Builder(mActivity)
                                .setContent(mMoreContentBean.getDocument())
                                .setRightBtnText("朕知道了").
                                setRightCallBack(new AlertFragmentDialog.RightClickCallBack() {
                                    @Override
                                    public void dialogRightBtnClick() {

                                    }
                                }).setCancel(false).build();
                    }
                });
            }
        } else {
            mTcProgress.setVisibility(View.GONE);
            mMoneyStatu.setVisibility(View.VISIBLE);
            mMoneyStatu.setText("额度未激活");
            mTvRemainingBorrow.setVisibility(View.GONE);
            mIvQuery.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MobclickAgent.onEvent(getActivity(), "ME_noVer");
                    TCAgent.onEvent(getActivity(), "ME_noVer");
                    new AlertFragmentDialog.Builder(mActivity)
                            .setContent("您当前未完成必填认证，额度未激活")
                            .setRightBtnText("去认证")
                            .setRightCallBack(new AlertFragmentDialog.RightClickCallBack() {
                                @Override
                                public void dialogRightBtnClick() {
                                    MobclickAgent.onEvent(getActivity(), "ME_gotoVer");
                                    TCAgent.onEvent(getActivity(), "ME_gotoVer");
                                    Intent intent = new Intent(getActivity(), AuthenticationVerifityActivity.class);
                                    intent.putExtra("authStep", mAuthStep);
                                    intent.putExtra("phoneUrl", mPhoneUrl);
                                    intent.putExtra("zmxyUrl", mZmxyUrl);
                                    startActivity(intent);
                                }
                            }).setLeftBtnText("取消").setLeftCallBack(new AlertFragmentDialog.LeftClickCallBack() {
                        @Override
                        public void dialogLeftBtnClick() {
                            MobclickAgent.onEvent(getActivity(), "ME_cancleVer");
                            TCAgent.onEvent(getActivity(), "ME_cancleVer");
                        }
                    }).setCancel(false).build();
                }
            });
        }


    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            ToastUtil.showToast("分享成功");
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToastUtil.showToast("分享失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
        }
    };


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("我的"); //统计页面，"MainScreen"为页面名称，可自定义
        MobclickAgent.onEvent(mContext, "my");
        TCAgent.onPageStart(mContext, "我的");
        TCAgent.onEvent(mContext, "my");
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("我的");
        TCAgent.onPageEnd(mContext, "我的");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        fragment = null;
        unbinder.unbind();
    }

    private void setCreditLimitAnimation(final TextView view, final int maxMoney) {
        ValueAnimator animator = ValueAnimator.ofInt(0, maxMoney)
                .setDuration(1000);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                view.setText(String.valueOf(animation.getAnimatedValue()));
            }
        });
        animator.start();
    }

    @OnClick({R.id.layout_perfect, R.id.layout_lend_record, R.id.layout_bank,
            R.id.layout_invitation_code, R.id.layout_message,
            R.id.layout_help, R.id.layout_qq, R.id.layout_coupon})
    public void onClick(View view) {
        /**
         * 防止多次点击进入重复界面
         * 针对于startActivity启动
         * */
        if (Tool.isFastDoubleClick())
            return;

        switch (view.getId()) {
            case R.id.layout_perfect:
                MobclickAgent.onEvent(mContext, "perfect_information");
                TCAgent.onEvent(mContext, "perfect_information");
                startActivity(PerfectInformationActivity.class);
                break;
            case R.id.layout_lend_record:
                MobclickAgent.onEvent(mContext, "lend_record");
                TCAgent.onEvent(mContext, "lend_record");
                startActivity(new Intent(mActivity, TransactionRecordActivity.class)
                        .putExtra("shouyijie_url", mMoreContentBean.getIncrease_credit_url().getShouyijie_url()));
                break;
            case R.id.layout_bank:
                MobclickAgent.onEvent(mContext, "proceeds_bank");
                TCAgent.onEvent(mContext, "proceeds_bank");
                if (mMoreContentBean != null) {
                    try {
                        if (mMoreContentBean.getVerify_info().getReal_verify_status().equals("1")) {
                            //if (mMoreContentBean.getVerify_info().getReal_bind_bank_card_status().equals("1")) {
                            Intent intent = new Intent(mActivity, WebViewActivity.class);
                            intent.putExtra("url", mMoreContentBean.getCard_url());
                            startActivity(intent);
                            /*} else {
                                startActivity(AddBankCardActivity.class);
                            }*/
                        } else {
                            new AlertFragmentDialog.Builder(mActivity)
                                    .setContent("亲,请先填写个人信息哦~")
                                    .setRightBtnText("确定")
                                    .setRightCallBack(new AlertFragmentDialog.RightClickCallBack() {
                                        @Override
                                        public void dialogRightBtnClick() {
                                            startActivity(PerfectInformationActivity.class);
                                        }
                                    }).setCancel(true).build();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    mPresenter.getInfo();
                }
                break;
            case R.id.layout_coupon:
                startActivityForResult(CouponActivity.class, 1024);
                break;
            case R.id.layout_invitation_code:
                Bundle invitation = new Bundle();
                invitation.putString("url", App.getConfig().INVITATION_CODE);
                startActivity(WebViewActivity.class, invitation);
                break;
            case R.id.layout_message:
                MobclickAgent.onEvent(mContext, "message");
                TCAgent.onEvent(mContext, "message");
                Bundle message = new Bundle();
                message.putString("url", App.getConfig().ACTIVITY_CENTER);
                startActivity(WebViewActivity.class, message);
                break;
            case R.id.layout_help:
                MobclickAgent.onEvent(mContext, "my_help");
                TCAgent.onEvent(mContext, "my_help");
                Bundle help = new Bundle();
                help.putString("url", App.getConfig().HELP);
                startActivity(WebViewActivity.class, help);
                break;
            case R.id.layout_qq:
                MobclickAgent.onEvent(mContext, "customer_service");
                TCAgent.onEvent(mContext, "customer_service");
                Information info = new Information();
                info.setAppkey(Constant.SOBOT_KEY);
                info.setUseVoice(true);//是否使用语言
                info.setPhone(SpUtil.getString(Constant.CACHE_TAG_USERNAME));//传入用户名手机号
                info.setRealname(SpUtil.getString(Constant.CACHE_TAG_REAL_NAME));//用户名
                //开启 离线消息
                SobotApi.initSobotChannel(mContext);
                //设置隐藏几分钟之前的历史消息
                //time-查询时间(例:100-表示从现在起前100分钟的会话)  默认为0  表示不隐藏历史记录
                //设置当用户返回时推送评价 用户信息
                SobotApi.startSobotChat(mActivity, info);
                break;
        }
    }

    @Override
    public void userInfoSuccess(MoreContentBean result) {
        mLoadingLayout.setStatus(LoadingLayout.Success);
        mMoreContentBean = result;
        if (mMoreContentBean != null) {
            setData(mMoreContentBean);
        }
    }

    @Override
    public void showLoading(String content) {
        if (mMoreContentBean == null) {
            mLoadingLayout.setStatus(LoadingLayout.Loading);
        }
    }

    @Override
    public void stopLoading() {
        mRefresh.setRefreshing(false);
    }

    @Override
    public void showErrorMsg(String msg, String type) {
        ToastUtil.showToast(msg);
        if ("网络不可用".equals(msg)) {
            mLoadingLayout.setStatus(LoadingLayout.No_Network);
        } else {
            mLoadingLayout.setErrorText(msg)
                    .setStatus(LoadingLayout.Error);
        }
        mLoadingLayout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                mPresenter.getInfo();
            }
        });
    }

    @Override
    public void onRefresh() {
        mPresenter.getInfo();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }
}
